/* js for the worksheet page */
var Worksheet = {
	change:function(that){
		var $progress = $('.worksheet-progress');
		var value = $(that).attr('value');
		var $worksheetID = $('input[name=worksheetID]');
		var $title = $('.widget-form-title[uuid='+value+']');
		$progress.find('li.selected').removeClass('selected');
		$progress.find('li[uuid='+value+']').addClass('selected');
		$('.worksheet-summary.selected').removeClass('selected');
		$('.worksheet-summary[uuid='+value+']').addClass('selected');
		$('.summary .widget-form-title').addClass('hidden');
		$title.removeClass('hidden');
		$worksheetID.val(value);
	},
	onListKeydown:function(that,event){
		if(event.keyCode == 13){
			event.preventDefault();
		}
		var $this = $(that);
		if(that.value == ""){
			Worksheet._inputEmpty($this,event);
		} else{
			Worksheet._inputNotEmpty($this,event);
		}
	},
	_inputEmpty:function($this,event){
		// evaluate whether to remove next row
		var $li = $this.closest('li');
		var $next = $li.next();
		$li.addClass('empty');
		if($next.length > 0 && $next.find('input:last').val() == ''){
			$next.remove();
		} else if(event.keyCode == 13){
			$li.closest('form').find('button[name=save]').focus();
		}
		if(event.keyCode == 8){
			var $input = $li.prev().find('input:last');
			$input.selectRange($input.val().length);
			event.preventDefault();
		}
	},
	_inputNotEmpty:function($this,event){
		// evaluate whether to add another row
		var $li = $this.closest('li');
		var $next = $li.next();
		$li.removeClass('empty');
		var index = +$li.attr('index');
		if($next.length == 0){
			var $next = $li.clone();
			var newIndex = index+1;
			$next.attr('index',newIndex);
			$next.find('.index-show').text(newIndex+'.');
			$next.find('input:last').val('');
			$next.addClass('empty');
			$li.after($next);
		}
		if(event.keyCode == 13){
			$next.find('input:last').focus();
		}
	},
	removeListRow:function(that){
		var $this = $(that);
		var $li = $this.closest('li');
		var $ul = $li.closest('ul');
		$li.remove();
		Worksheet.renumberList($ul);
	},
	renumberList:function($ul){
		var index = 0;
		$ul.find('li').each(function(){
			index++;
			$(this).attr('index',index);
			$(this).find('.index-show').html(index+'.');
		});
	}
};